/**  
 * All rights Reserved, Designed By www.tydic.com
 * @Title:  Controller.java   
 * @Package com.axin.controller   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: axin     
 * @date:   2019年3月8日 下午11:40:39   
 * @version V1.0 
 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. 
 */
package com.axin.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.axin.common.entity.ApiToken;
import com.axin.common.entity.JsonResult;
import com.axin.common.exception.AccountLockException;
import com.axin.common.exception.ApiException;
import com.axin.common.exception.UnTokenException;
import com.axin.common.quartz.QuartzManager;
import com.axin.common.websocket.WebSocketServer;
import com.axin.entity.HbKeyPair;
import com.axin.entity.HbTask;
import com.axin.entity.HbUser;
import com.axin.job.JobB;
import com.axin.job.MyJob;
import com.axin.service.MessageService;
import com.axin.service.SchedulerService;
import com.axin.service.TaskService;

/**   
 * @Description: TODO 
 * @ClassName:  Controller
 * @author:  Axin 
 * @date:   2019年3月8日 下午11:40:39   
 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. 
 */
@Controller
@RequestMapping("/scheduler")
public class SchedulerController {
	
    //这个bean在spring中配置，可以直接注入
    @Autowired
    private QuartzManager quartzManager;
    
    @Autowired
    private SchedulerService schedulerService;
    
    @Autowired
    private TaskService taskService;
    
    @Autowired
    private MessageService messageService;
    
    private static WebSocketServer socketServer = new WebSocketServer();
    
    Logger logger = LoggerFactory.getLogger(SchedulerController.class);
 
    @RequestMapping(value = "startQuartz", method = RequestMethod.POST)
    @ResponseBody
    public String testQuartz(String quartzTime) throws Exception{
        logger.info("===========开始执行调度=========时间为 " + quartzTime);
        String cronStr = quartzManager.transCron(quartzTime);
        logger.info("======cron表达式========" + cronStr);
        quartzManager.addJobForTimeout("test", "test", "test", "test", MyJob.class, cronStr);    
        //quartzManager.modifyJobTime("test", "test", "test", "test", "0 50 10 * * ?");    
        //quartzManager.removeJob("test", "test", "test", "test");    
        //quartzManager.shutdownJobs();
        return "success";
    }
    
    @RequestMapping(value = "startTask", method =RequestMethod.POST)
    @ResponseBody
    public JsonResult startTask(HttpServletRequest request){
    	HbUser user = (HbUser)request.getAttribute("user");
    	HbKeyPair keyPair = (HbKeyPair)request.getAttribute("kPair");
    	ApiToken token = (ApiToken)request.getAttribute("apiToken");
    	if(token == null){
    		return new JsonResult(new UnTokenException("您尚未设置密钥，不能处理您的请求！"));
    	}
    	Map<String,Object> params = new HashMap<>();
    	params.put("userId", user.getId());
    	params.put("keyPair", keyPair);
    	params.put("token", token);
       quartzManager.addJobForInterval("test", "test", "test", "test", params,500,JobB.class);    
       return new JsonResult();
    }
    
    
    @RequestMapping(value = "startTaskById", method =RequestMethod.POST)
    @ResponseBody
    public JsonResult startTaskById(@RequestParam(value="id",required=true)Long id,HttpServletRequest request)
    					throws ApiException, AccountLockException, Exception{
    	HbUser user = (HbUser)request.getAttribute("user");
    	ApiToken token = (ApiToken)request.getAttribute("apiToken");
    	if(token == null){
    		return new JsonResult(new UnTokenException("您尚未设置密钥，不能处理您的请求！"));
    	}
    	schedulerService.startTaskById(token, id, user.getId());
        return new JsonResult();
    }
    
    @RequestMapping(value = "stopTaskById", method =RequestMethod.POST)
    @ResponseBody
    public JsonResult stopTaskById(@RequestParam(value="id",required=true)Long id,HttpServletRequest request)
    					throws ApiException, AccountLockException, Exception{
    	HbUser user = (HbUser)request.getAttribute("user");
    	ApiToken token = (ApiToken)request.getAttribute("apiToken");
    	if(token == null){
    		return new JsonResult(new UnTokenException("您尚未设置密钥，不能处理您的请求！"));
    	}
    	quartzManager.removeJob(id+"", id+"",id+"",id+"");
    	
    	HbTask task = new HbTask();
    	task.setId(id);
    	task.setState("0");
    	this.taskService.updateTaskById(task, user.getId());
    	Thread.sleep(1500);
    	this.messageService.sendConsoleMessage(user.getId(), "任务已停止。");
        return new JsonResult();
    }
 
    @RequestMapping(value = "stopTask", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult stopTask(HttpServletRequest request) throws Exception{
    	HbUser user = (HbUser)request.getAttribute("user");
        quartzManager.removeJob("test", "test", "test", "test");
        DateTime dateTime = new DateTime();
    	String string = dateTime.toString("yyyy-MM-dd hh:mm:ss");
    	//socketServer.sendMessageToUser("CONSOLE_"+user.getId(), string+ " --> 执止了任务");
        return new JsonResult();
    }

}
